package com.xzlf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xzlf.domain.NovelChapter;
import com.xzlf.domain.WebSite;
import com.xzlf.mapper.NovelChapterMapper;
import com.xzlf.service.WebSiteService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzlf.mapper.NovelInfoMapper;
import com.xzlf.domain.NovelInfo;
import com.xzlf.service.NovelInfoService;

@Service
public class NovelInfoServiceImpl extends ServiceImpl<NovelInfoMapper, NovelInfo> implements NovelInfoService {

    private static List<NovelChapter> list = new ArrayList<>();

    @Autowired
    private NovelChapterMapper novelChapterMapper;

    @Autowired
    private WebSiteService webSiteService;

    @Override
    public boolean saveNovel(String url, int popNum, NovelInfo novelInfo) {
        try {
            save(novelInfo);
            NovelInfo info = getById(novelInfo.getId());
            saveNovelChapter(info, popNum, url);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    private void saveNovelChapter(NovelInfo info, int popNum, String url) throws IOException {
        Document document = Jsoup.connect(url).get();
        Document parse = Jsoup.parse(document.html());
        Integer pid = info.getPid();
        WebSite webSite = webSiteService.getById(pid);
        Elements elements = parse.select(webSite.getTitleSelect());
        System.out.println(elements.size());
        for (Element element : elements) {
            NovelChapter novelChapter = new NovelChapter();
            novelChapter.setPid(pid);
            novelChapter.setTid(info.getId());
            novelChapter.setTitle(element.text().trim());
            novelChapter.setUri(element.attr("href").trim());
            list.add(novelChapter);
        }

        for (int i = 0; i < popNum; i++) {
            list.remove(0);
        }
        novelChapterMapper.saveBatch(list);
    }

    @Override
    public List<NovelInfo> findNovel(int pid) {
        List<NovelInfo> list = list(new LambdaQueryWrapper<NovelInfo>()
                .eq(pid != 0, NovelInfo::getPid, pid));
        return list;
    }
}
